package com.guaju.yueshangLife.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Entity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsoluteLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.activity.CaculateActivity;
import com.guaju.yueshangLife.activity.CartActivity;
import com.guaju.yueshangLife.activity.LoginActivity;
import com.guaju.yueshangLife.activity.MainActivity;
import com.guaju.yueshangLife.activity.mine.ServiceActivity;
import com.guaju.yueshangLife.adapter.ShoppingCartAdapter;
import com.guaju.yueshangLife.base.BaseFragment;
import com.guaju.yueshangLife.bean.CartGoods;
import com.guaju.yueshangLife.bean.CartStringBean;
import com.guaju.yueshangLife.bean.DelResultBean;
import com.guaju.yueshangLife.databinding.FragmentCartBinding;
import com.guaju.yueshangLife.net.ApiEntity;
import com.guaju.yueshangLife.utils.PreferenceUtil;
import com.guaju.yueshangLife.utils.ToastUtil;
import com.guaju.yueshangLife.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * Created by guaju on 2018/9/21.
 */

public class CartFragment extends BaseFragment<FragmentCartBinding> implements View.OnClickListener
        , ShoppingCartAdapter.CheckInterface, ShoppingCartAdapter.ModifyCountInterface {
    private static final String TAG = "ShoppingCartActivity";
//    Button btnBack;
//    //全选
//    CheckBox ckAll;
//    //总额
//    TextView tvShowPrice;
//    //结算
//    TextView tvSettlement;
//    //编辑
//    TextView btnEdit;//tv_edit

    ListView list_shopping_cart;
    private ShoppingCartAdapter shoppingCartAdapter;
    private boolean flag = false;
    private List<CartGoods> cartGoodsList = new ArrayList<>();
    private boolean mSelect;
    private double totalPrice = 0.00;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量
    private String attribute;
    private JSONObject price;
    private JSONObject cover;
    private JSONArray description;
    private String color;
    private String size;
    private int id;
    private boolean isFirst = true;
    ArrayList<Integer> deleteList = new ArrayList<>();
    private MainActivity mainActivity;
    private CartActivity cartActivity;
    private View news_loading;

    private void initView() {
        bindingView.cartTop.flBack.setVisibility(View.GONE);
        bindingView.llEmptyCart.setVisibility(View.GONE);

        bindingView.ckAll.setChecked(false);
        cartGoodsList.clear();
        statistics();


        setListener();

        if (PreferenceUtil.getIsLogin()) {
            bindingView.unloginbar.setVisibility(View.GONE);
        } else {
            bindingView.unloginbar.setVisibility(View.VISIBLE);
        }

        addProgressPic();
    }

    private void setListener() {
        bindingView.llModeEdit.setVisibility(View.GONE);
        bindingView.ckAll.setOnClickListener(this);
        bindingView.btSubmmitOrder.setOnClickListener(this);
        bindingView.btDelete.setOnClickListener(this);
        bindingView.cartTop.tvManage.setVisibility(View.VISIBLE);
        bindingView.cartTop.tvManage.setOnClickListener(this);

        if (!PreferenceUtil.getIsLogin()) {
            bindingView.unloginbar.setVisibility(View.VISIBLE);
            bindingView.unloginbar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
                }
            });
            bindingView.cartTop.rlMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
                }
            });
            bindingView.cartTop.tvManage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
                }
            });

        } else {
            bindingView.cartTop.rlMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getActivity(), ServiceActivity.class));
                }
            });
            bindingView.unloginbar.setVisibility(View.GONE);
        }
        bindingView.llEmptyCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity() instanceof MainActivity) {
                    MainActivity activity = (MainActivity) getActivity();
                    activity.switchToHomeFragment();
                } else if (getActivity() instanceof CartActivity) {
                    CartActivity activity = (CartActivity) getActivity();
                    activity.startActivity(new Intent(activity, MainActivity.class));
                    getActivity().finish();
                }
            }
        });
    }

    protected void loadData() {
        ApiEntity.cartString();
        bindingView.listShoppingCart.setVisibility(View.VISIBLE);
        bindingView.llEmptyCart.setVisibility(View.GONE);
    }

    //    @Override
//    public void onResume() {
//        super.onResume();
////        mainActivity.setTab_position(2);
////        if (!isFirst) {
////            loadData();
////        }
//
//    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden){
            loadData();
        }
    }

    @Override
    protected void onVisible() {

        if (!PreferenceUtil.getIsLogin()) {
            bindingView.unloginbar.setVisibility(View.VISIBLE);
        } else {
            bindingView.unloginbar.setVisibility(View.GONE);
        }

        loadData();


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //全选按钮
            case R.id.ck_all:
                if (cartGoodsList.size() != 0) {
                    if (bindingView.ckAll.isChecked()) {
                        for (int i = 0; i < cartGoodsList.size(); i++) {
                            cartGoodsList.get(i).setChoosed(true);
                            //要操作的删除集合
                            deleteList.add(i);
                        }
                        shoppingCartAdapter.notifyDataSetChanged();
                    } else {
                        for (int i = 0; i < cartGoodsList.size(); i++) {
                            cartGoodsList.get(i).setChoosed(false);
                            //要操作的删除集合
                            deleteList.clear();
                        }
                        shoppingCartAdapter.notifyDataSetChanged();
                    }
                } else {
                    Toast.makeText(mainActivity, "购物车为空,去逛逛吧~", Toast.LENGTH_SHORT).show();
                }
                statistics();
                break;
            case R.id.tv_manage:
                if (!cartGoodsList.isEmpty()) {
                    flag = !flag;
                    if (flag) {
                        setShowManage();
                    } else {
                        setShowComplete();

                    }

                } else {
                    ToastUtil.show("购物车为空,去逛逛吧~");
                }
                break;
            case R.id.bt_delete:
                AlertDialog alert = new AlertDialog.Builder(getActivity()).create();
                alert.setTitle("操作提示");
                alert.setMessage("您确定要将这些商品从购物车中移除吗？");
                alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        });
                alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                childDelete(deleteList);//删除 目前只是从item中移除

                            }
                        });
                alert.show();


                break;
            case R.id.bt_submmit_order: //结算
                lementOnder();
                break;
            case R.id.btn_back:
                getActivity().finish();
                break;
        }
    }

    private void setShowComplete() {
        bindingView.cartTop.tvManage.setText("完成");
        //展示删除商品布局
        bindingView.llModeSubmit.setVisibility(View.GONE);
        bindingView.llModeEdit.setVisibility(View.VISIBLE);
    }

    private void setShowManage() {
        bindingView.cartTop.tvManage.setText("管理");
//                    隐藏删除商品布局
        bindingView.llModeSubmit.setVisibility(View.VISIBLE);
        bindingView.llModeEdit.setVisibility(View.GONE);
    }

    /**
     * 结算订单、支付
     */
    private void lementOnder() {
        //选中的需要提交的商品清单

        if (cartGoodsList == null || cartGoodsList.isEmpty()) {
            ToastUtil.show("购物车为空，去逛逛吧");
            return;
        }

        for (CartGoods bean : cartGoodsList) {
            boolean choosed = bean.isChoosed();
            if (choosed) {
                String shoppingName = bean.getTitle();
                int count = bean.getCount();
                double price = Double.parseDouble(bean.getPrice());
                int size = bean.getDressSize();
                String attribute = bean.getAttribute();
                int id = bean.getId();
                Log.d(TAG, id + "----id---" + shoppingName + "---" + count + "---" + price + "--size----" + size + "--attr---" + attribute);
            }
        }
//        ToastUtil.show("总价：" + totalPrice);


        if (0 != totalCount) {

            //跳转到支付界面
            Intent intent = new Intent(getActivity(), CaculateActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(CaculateActivity.LIST, (Serializable) cartGoodsList);
            bundle.putInt(CaculateActivity.TOTAL_COUNT, totalCount);
            bundle.putDouble(CaculateActivity.TOTAL_FEE, totalPrice);
            intent.putExtras(bundle);
            startActivity(intent);
        } else {
            Toast.makeText(mainActivity, "未选择商品", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 单选
     *
     * @param position  组元素位置
     * @param isChecked 组元素选中与否
     */
    @Override
    public void checkGroup(int position, boolean isChecked) {
        cartGoodsList.get(position).setChoosed(isChecked);
        if (isAllCheck())
            bindingView.ckAll.setChecked(true);
        else
            bindingView.ckAll.setChecked(false);
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }

    /**
     * 遍历list集合
     *
     * @return
     */
    private boolean isAllCheck() {

        for (CartGoods group : cartGoodsList) {
            if (!group.isChoosed())
                return false;
        }
        return true;
    }

    /**
     * 统计操作
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作
     * 3.给底部的textView进行数据填充
     */
    public void statistics() {
        totalCount = 0;
        totalPrice = 0.00;
        for (int i = 0; i < cartGoodsList.size(); i++) {
            CartGoods shoppingCartBean = cartGoodsList.get(i);
            if (shoppingCartBean.isChoosed()) {
                totalCount++;
                totalPrice += Double.parseDouble(shoppingCartBean.getPrice()) * shoppingCartBean.getCount();
            }
        }
        bindingView.tvShowPrice.setText(totalPrice + "");
        bindingView.btSubmmitOrder.setText("去结算(" + totalCount + ")");
        if (cartGoodsList == null || cartGoodsList.isEmpty()) {
            setShowManage();
        }
    }

    /**
     * 增加
     *
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doIncrease(int position, View showCountView, boolean isChecked) {
        CartGoods shoppingCartBean = cartGoodsList.get(position);
        int currentCount = shoppingCartBean.getCount();
        currentCount++;
        /**
         * 更新购物车接口
         */
        int id = shoppingCartBean.getId();
        ApiEntity.updateCartGoods(id, currentCount);

        shoppingCartBean.setCount(currentCount);
        ((TextView) showCountView).setText(currentCount + "");
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }

    /**
     * 删减
     *
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doDecrease(int position, View showCountView, boolean isChecked) {
        CartGoods shoppingCartBean = cartGoodsList.get(position);
        int currentCount = shoppingCartBean.getCount();
        if (currentCount == 1) {
            return;
        }
        currentCount--;

        /**
         * 更新购物车接口
         */

        int id = shoppingCartBean.getId();
        ApiEntity.updateCartGoods(id, currentCount);

        shoppingCartBean.setCount(currentCount);
        ((TextView) showCountView).setText(currentCount + "");
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }

    /**
     * 删除
     */
    @Override
    public void childDelete(ArrayList<Integer> deleteLists) {
        String delStr = "";
        HashMap<Integer, CartGoods> map = new HashMap<>();
        for (int m = 0; m < cartGoodsList.size(); m++) {
            map.put(m, cartGoodsList.get(m));
        }

        for (Integer i : deleteLists) {
            if (map.containsKey(i)) {

                CartGoods remove = map.remove(i);

                if (TextUtils.isEmpty(delStr)) {
                    delStr = remove.getId() + "";
                } else {
                    delStr = delStr + "," + remove.getId();
                }
            }
        }
        cartGoodsList.clear();
        if (!map.isEmpty()) {
            Set<Integer> integers = map.keySet();
            for (Integer i : integers) {
                CartGoods cartGoods = map.get(i);
                cartGoodsList.add(cartGoods);
            }


        }
        if (TextUtils.isEmpty(delStr)) {
            setShowManage();
        } else {
            ApiEntity.delFromCart(delStr);
        }

    }

    @Override
    public void onDelChecked(int position) {
        deleteList.add(position);
    }

    @Override
    public void onDelUnChecked(int position) {
        if (deleteList.contains(position)) {
            deleteList.remove(position);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        EventBus.getDefault().register(this);
        showContentView();
        if (getActivity() instanceof MainActivity) {
            mainActivity = (MainActivity) getActivity();
        } else {
            cartActivity = (CartActivity) getActivity();
        }
//        loadData();
    }

    @Override
    public int setContent() {
        return R.layout.fragment_cart;
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDelFromCart(DelResultBean bean) {
        news_loading.setVisibility(View.GONE);
        int code = bean.getCode();
        if (code == 200) {
            shoppingCartAdapter.notifyDataSetChanged();
            if (cartGoodsList == null || cartGoodsList.isEmpty()) {
                showEmpty();
            }
            statistics();
        } else {
            ToastUtil.show(bean.getMsg());
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCart(CartStringBean cartStringBean) {
        news_loading.setVisibility(View.GONE);
        bindingView.listShoppingCart.setVisibility(View.VISIBLE);
        bindingView.llEmptyCart.setVisibility(View.GONE);
        cartGoodsList.clear();

        try {
            String cartTotal = cartStringBean.getInfo();
            JSONObject jsonObject = new JSONObject(cartTotal);
            int code = jsonObject.getInt("code");
            if (200 == code) {
                JSONArray data = jsonObject.getJSONArray("data");
                if (data != null && data.length() > 0) {
                    cartGoodsList.clear();
                    bindingView.llEmptyCart.setVisibility(View.GONE);
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject goods = data.getJSONObject(i);
                        if (goods.has("price")) {
                            price = goods.getJSONObject("price");
                        }
                        if (goods.has("cover")) {
                            cover = goods.getJSONObject("cover");
                        }
                        if (goods.has("id")) {
                            id = goods.getInt("id");
                        }
                        if (goods.has("description")) {
                            description = goods.getJSONArray("description");
                            StringBuffer sb = new StringBuffer();
                            for (int j = 0; j < description.length(); j++) {
                                sb.append(";");
                                sb.append(description.getString(j));

                            }
                            String s = sb.toString();
                            attribute = s.substring(1, s.length());
                        }
                        color = description.getString(0);
                        if (description.length() > 0) {
                            size = description.getString(1);
                        }
                        CartGoods cartGoods = new CartGoods();
                        if (goods.has("name")) {
                            cartGoods.setTitle(goods.getString("name"));
                        }
                        cartGoods.setId(id);
                        cartGoods.setSize(size);
                        cartGoods.setColor(color);
                        cartGoods.setAttribute(attribute);
                        cartGoods.setStock(goods.getInt("stock"));
                        cartGoods.setPrice(price.getString("current"));
                        cartGoods.setOriginal(price.getString("original"));
                        cartGoods.setWholesale(price.getString("wholesale"));
                        cartGoods.setCount(goods.getInt("number"));
                        cartGoods.setImageUrl(cover.getString("host") + cover.getString("path"));
                        cartGoodsList.add(cartGoods);
                        isFirst = false;
                    }
                } else {
                    bindingView.llEmptyCart.setVisibility(View.VISIBLE);
                    bindingView.listShoppingCart.setVisibility(View.GONE);
                }
                shoppingCartAdapter = new ShoppingCartAdapter(getActivity());
                shoppingCartAdapter.setCheckInterface(this);
                shoppingCartAdapter.setModifyCountInterface(this);
                bindingView.listShoppingCart.setAdapter(shoppingCartAdapter);
                shoppingCartAdapter.setShoppingCartBeanList(cartGoodsList);
                bindingView.ckAll.setVisibility(View.VISIBLE);
                bindingView.tvAll.setVisibility(View.VISIBLE);
                if (cartGoodsList.isEmpty()) {
                    showEmpty();
                }
            } else {
                showEmpty();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void showEmpty() {
        news_loading.setVisibility(View.GONE);
        bindingView.listShoppingCart.setVisibility(View.GONE);
        bindingView.llEmptyCart.setVisibility(View.VISIBLE);
        bindingView.ckAll.setVisibility(View.INVISIBLE);
        bindingView.tvAll.setVisibility(View.INVISIBLE);
    }


    public void addProgressPic() {
        news_loading = View.inflate(getActivity(), R.layout.loading, null);
        news_loading.setLayoutParams(new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.MATCH_PARENT, AbsoluteLayout.LayoutParams.MATCH_PARENT, 0, 0));
        Bitmap mBgBitmap = Utils.readBitMap(getActivity(), R.drawable.loading_order_detail);
        news_loading.setBackgroundDrawable(new BitmapDrawable(mBgBitmap));
        bindingView.rlContainer.addView(news_loading);
        news_loading.setVisibility(View.VISIBLE);
    }



}

